connection.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  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 * 5 / 4
  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. congestionControl bool
  160. output *BufferedSegmentWriter
  161. dataUpdater *Updater
  162. pingUpdater *Updater
  163. }
  164. // NewConnection create a new KCP connection between local and remote.
  165. func NewConnection(conv uint16, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block internet.Authenticator, config *Config) *Connection {
  166. log.Info("KCP|Connection: creating connection ", conv)
  167. conn := new(Connection)
  168. conn.local = local
  169. conn.remote = remote
  170. conn.block = block
  171. conn.writer = writerCloser
  172. conn.since = nowMillisec()
  173. conn.dataInputCond = sync.NewCond(new(sync.Mutex))
  174. conn.dataOutputCond = sync.NewCond(new(sync.Mutex))
  175. conn.Config = config
  176. authWriter := &AuthenticationWriter{
  177. Authenticator: block,
  178. Writer: writerCloser,
  179. Config: config,
  180. }
  181. conn.conv = conv
  182. conn.output = NewSegmentWriter(authWriter)
  183. conn.mss = authWriter.Mtu() - DataSegmentOverhead
  184. conn.roundTrip = &RoundTripInfo{
  185. rto: 100,
  186. minRtt: config.Tti.GetValue(),
  187. }
  188. conn.interval = config.Tti.GetValue()
  189. conn.receivingWorker = NewReceivingWorker(conn)
  190. conn.congestionControl = config.Congestion
  191. conn.sendingWorker = NewSendingWorker(conn)
  192. isTerminating := func() bool {
  193. return conn.State().Is(StateTerminating, StateTerminated)
  194. }
  195. isTerminated := func() bool {
  196. return conn.State() == StateTerminated
  197. }
  198. conn.dataUpdater = NewUpdater(
  199. conn.interval,
  200. predicate.Not(isTerminating).And(predicate.Any(conn.sendingWorker.UpdateNecessary, conn.receivingWorker.UpdateNecessary)),
  201. isTerminating,
  202. conn.updateTask)
  203. conn.pingUpdater = NewUpdater(
  204. 5000, // 5 seconds
  205. predicate.Not(isTerminated),
  206. isTerminated,
  207. conn.updateTask)
  208. conn.pingUpdater.WakeUp()
  209. return conn
  210. }
  211. func (this *Connection) Elapsed() uint32 {
  212. return uint32(nowMillisec() - this.since)
  213. }
  214. // Read implements the Conn Read method.
  215. func (this *Connection) Read(b []byte) (int, error) {
  216. if this == nil {
  217. return 0, io.EOF
  218. }
  219. for {
  220. if this.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  221. return 0, io.EOF
  222. }
  223. nBytes := this.receivingWorker.Read(b)
  224. if nBytes > 0 {
  225. return nBytes, nil
  226. }
  227. if this.State() == StatePeerTerminating {
  228. return 0, io.EOF
  229. }
  230. var timer *time.Timer
  231. if !this.rd.IsZero() {
  232. duration := this.rd.Sub(time.Now())
  233. if duration <= 0 {
  234. return 0, ErrIOTimeout
  235. }
  236. timer = time.AfterFunc(duration, this.dataInputCond.Signal)
  237. }
  238. this.dataInputCond.L.Lock()
  239. this.dataInputCond.Wait()
  240. this.dataInputCond.L.Unlock()
  241. if timer != nil {
  242. timer.Stop()
  243. }
  244. if !this.rd.IsZero() && this.rd.Before(time.Now()) {
  245. return 0, ErrIOTimeout
  246. }
  247. }
  248. }
  249. // Write implements the Conn Write method.
  250. func (this *Connection) Write(b []byte) (int, error) {
  251. totalWritten := 0
  252. for {
  253. if this == nil || this.State() != StateActive {
  254. return totalWritten, io.ErrClosedPipe
  255. }
  256. nBytes := this.sendingWorker.Push(b[totalWritten:])
  257. this.dataUpdater.WakeUp()
  258. if nBytes > 0 {
  259. totalWritten += nBytes
  260. if totalWritten == len(b) {
  261. return totalWritten, nil
  262. }
  263. }
  264. var timer *time.Timer
  265. if !this.wd.IsZero() {
  266. duration := this.wd.Sub(time.Now())
  267. if duration <= 0 {
  268. return totalWritten, ErrIOTimeout
  269. }
  270. timer = time.AfterFunc(duration, this.dataOutputCond.Signal)
  271. }
  272. this.dataOutputCond.L.Lock()
  273. this.dataOutputCond.Wait()
  274. this.dataOutputCond.L.Unlock()
  275. if timer != nil {
  276. timer.Stop()
  277. }
  278. if !this.wd.IsZero() && this.wd.Before(time.Now()) {
  279. return totalWritten, ErrIOTimeout
  280. }
  281. }
  282. }
  283. func (this *Connection) SetState(state State) {
  284. current := this.Elapsed()
  285. atomic.StoreInt32((*int32)(&this.state), int32(state))
  286. atomic.StoreUint32(&this.stateBeginTime, current)
  287. log.Debug("KCP|Connection: #", this.conv, " entering state ", state, " at ", current)
  288. switch state {
  289. case StateReadyToClose:
  290. this.receivingWorker.CloseRead()
  291. case StatePeerClosed:
  292. this.sendingWorker.CloseWrite()
  293. case StateTerminating:
  294. this.receivingWorker.CloseRead()
  295. this.sendingWorker.CloseWrite()
  296. this.pingUpdater.interval = time.Second
  297. case StatePeerTerminating:
  298. this.sendingWorker.CloseWrite()
  299. this.pingUpdater.interval = time.Second
  300. case StateTerminated:
  301. this.receivingWorker.CloseRead()
  302. this.sendingWorker.CloseWrite()
  303. this.pingUpdater.interval = time.Second
  304. this.dataUpdater.WakeUp()
  305. this.pingUpdater.WakeUp()
  306. go this.Terminate()
  307. }
  308. }
  309. // Close closes the connection.
  310. func (this *Connection) Close() error {
  311. if this == nil {
  312. return ErrClosedConnection
  313. }
  314. this.dataInputCond.Broadcast()
  315. this.dataOutputCond.Broadcast()
  316. state := this.State()
  317. if state.Is(StateReadyToClose, StateTerminating, StateTerminated) {
  318. return ErrClosedConnection
  319. }
  320. log.Info("KCP|Connection: Closing connection to ", this.remote)
  321. if state == StateActive {
  322. this.SetState(StateReadyToClose)
  323. }
  324. if state == StatePeerClosed {
  325. this.SetState(StateTerminating)
  326. }
  327. if state == StatePeerTerminating {
  328. this.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 (this *Connection) LocalAddr() net.Addr {
  334. if this == nil {
  335. return nil
  336. }
  337. return this.local
  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 (this *Connection) RemoteAddr() net.Addr {
  341. if this == nil {
  342. return nil
  343. }
  344. return this.remote
  345. }
  346. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  347. func (this *Connection) SetDeadline(t time.Time) error {
  348. if err := this.SetReadDeadline(t); err != nil {
  349. return err
  350. }
  351. if err := this.SetWriteDeadline(t); err != nil {
  352. return err
  353. }
  354. return nil
  355. }
  356. // SetReadDeadline implements the Conn SetReadDeadline method.
  357. func (this *Connection) SetReadDeadline(t time.Time) error {
  358. if this == nil || this.State() != StateActive {
  359. return ErrClosedConnection
  360. }
  361. this.rd = t
  362. return nil
  363. }
  364. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  365. func (this *Connection) SetWriteDeadline(t time.Time) error {
  366. if this == nil || this.State() != StateActive {
  367. return ErrClosedConnection
  368. }
  369. this.wd = t
  370. return nil
  371. }
  372. // kcp update, input loop
  373. func (this *Connection) updateTask() {
  374. this.flush()
  375. }
  376. func (this *Connection) FetchInputFrom(conn io.Reader) {
  377. go func() {
  378. payload := alloc.NewLocalBuffer(2048)
  379. defer payload.Release()
  380. for this.State() != StateTerminated {
  381. payload.Reset()
  382. nBytes, err := conn.Read(payload.Value)
  383. if err != nil {
  384. return
  385. }
  386. payload.Slice(0, nBytes)
  387. if this.block.Open(payload) {
  388. this.Input(payload.Value)
  389. }
  390. }
  391. }()
  392. }
  393. func (this *Connection) Reusable() bool {
  394. return false
  395. }
  396. func (this *Connection) SetReusable(b bool) {}
  397. func (this *Connection) Terminate() {
  398. if this == nil || this.writer == nil {
  399. return
  400. }
  401. log.Info("KCP|Connection: Terminating connection to ", this.RemoteAddr())
  402. //this.SetState(StateTerminated)
  403. this.dataInputCond.Broadcast()
  404. this.dataOutputCond.Broadcast()
  405. this.writer.Close()
  406. }
  407. func (this *Connection) HandleOption(opt SegmentOption) {
  408. if (opt & SegmentOptionClose) == SegmentOptionClose {
  409. this.OnPeerClosed()
  410. }
  411. }
  412. func (this *Connection) OnPeerClosed() {
  413. state := this.State()
  414. if state == StateReadyToClose {
  415. this.SetState(StateTerminating)
  416. }
  417. if state == StateActive {
  418. this.SetState(StatePeerClosed)
  419. }
  420. }
  421. // Input when you received a low level packet (eg. UDP packet), call it
  422. func (this *Connection) Input(data []byte) int {
  423. current := this.Elapsed()
  424. atomic.StoreUint32(&this.lastIncomingTime, current)
  425. var seg Segment
  426. for {
  427. seg, data = ReadSegment(data)
  428. if seg == nil {
  429. break
  430. }
  431. switch seg := seg.(type) {
  432. case *DataSegment:
  433. this.HandleOption(seg.Option)
  434. this.receivingWorker.ProcessSegment(seg)
  435. this.dataInputCond.Signal()
  436. this.dataUpdater.WakeUp()
  437. case *AckSegment:
  438. this.HandleOption(seg.Option)
  439. this.sendingWorker.ProcessSegment(current, seg, this.roundTrip.Timeout())
  440. this.dataOutputCond.Signal()
  441. this.dataUpdater.WakeUp()
  442. case *CmdOnlySegment:
  443. this.HandleOption(seg.Option)
  444. if seg.Command == CommandTerminate {
  445. state := this.State()
  446. if state == StateActive ||
  447. state == StatePeerClosed {
  448. this.SetState(StatePeerTerminating)
  449. } else if state == StateReadyToClose {
  450. this.SetState(StateTerminating)
  451. } else if state == StateTerminating {
  452. this.SetState(StateTerminated)
  453. }
  454. }
  455. this.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
  456. this.receivingWorker.ProcessSendingNext(seg.SendingNext)
  457. this.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
  458. seg.Release()
  459. default:
  460. }
  461. }
  462. return 0
  463. }
  464. func (this *Connection) flush() {
  465. current := this.Elapsed()
  466. if this.State() == StateTerminated {
  467. return
  468. }
  469. if this.State() == StateActive && current-atomic.LoadUint32(&this.lastIncomingTime) >= 30000 {
  470. this.Close()
  471. }
  472. if this.State() == StateReadyToClose && this.sendingWorker.IsEmpty() {
  473. this.SetState(StateTerminating)
  474. }
  475. if this.State() == StateTerminating {
  476. log.Debug("KCP|Connection: #", this.conv, " sending terminating cmd.")
  477. this.Ping(current, CommandTerminate)
  478. this.output.Flush()
  479. if current-atomic.LoadUint32(&this.stateBeginTime) > 8000 {
  480. this.SetState(StateTerminated)
  481. }
  482. return
  483. }
  484. if this.State() == StatePeerTerminating && current-atomic.LoadUint32(&this.stateBeginTime) > 4000 {
  485. this.SetState(StateTerminating)
  486. }
  487. if this.State() == StateReadyToClose && current-atomic.LoadUint32(&this.stateBeginTime) > 15000 {
  488. this.SetState(StateTerminating)
  489. }
  490. // flush acknowledges
  491. this.receivingWorker.Flush(current)
  492. this.sendingWorker.Flush(current)
  493. if current-atomic.LoadUint32(&this.lastPingTime) >= 1000 {
  494. this.Ping(current, CommandPing)
  495. }
  496. // flash remain segments
  497. this.output.Flush()
  498. }
  499. func (this *Connection) State() State {
  500. return State(atomic.LoadInt32((*int32)(&this.state)))
  501. }
  502. func (this *Connection) Ping(current uint32, cmd Command) {
  503. seg := NewCmdOnlySegment()
  504. seg.Conv = this.conv
  505. seg.Command = cmd
  506. seg.ReceivinNext = this.receivingWorker.nextNumber
  507. seg.SendingNext = this.sendingWorker.firstUnacknowledged
  508. seg.PeerRTO = this.roundTrip.Timeout()
  509. if this.State() == StateReadyToClose {
  510. seg.Option = SegmentOptionClose
  511. }
  512. this.output.Write(seg)
  513. atomic.StoreUint32(&this.lastPingTime, current)
  514. seg.Release()
  515. }