connection.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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. conn.dataUpdater = NewUpdater(
  195. conn.interval,
  196. predicate.Any(conn.sendingWorker.UpdateNecessary, conn.receivingWorker.UpdateNecessary),
  197. func() bool {
  198. return conn.State() == StateTerminated
  199. },
  200. conn.updateTask)
  201. conn.pingUpdater = NewUpdater(
  202. 3000, // 3 seconds
  203. func() bool { return conn.State() != StateTerminated },
  204. func() bool { return conn.State() == StateTerminated },
  205. conn.updateTask)
  206. return conn
  207. }
  208. func (this *Connection) Elapsed() uint32 {
  209. return uint32(nowMillisec() - this.since)
  210. }
  211. // Read implements the Conn Read method.
  212. func (this *Connection) Read(b []byte) (int, error) {
  213. if this == nil {
  214. return 0, io.EOF
  215. }
  216. for {
  217. if this.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
  218. return 0, io.EOF
  219. }
  220. nBytes := this.receivingWorker.Read(b)
  221. if nBytes > 0 {
  222. return nBytes, nil
  223. }
  224. if this.State() == StatePeerTerminating {
  225. return 0, io.EOF
  226. }
  227. var timer *time.Timer
  228. if !this.rd.IsZero() {
  229. duration := this.rd.Sub(time.Now())
  230. if duration <= 0 {
  231. return 0, ErrIOTimeout
  232. }
  233. timer = time.AfterFunc(duration, this.dataInputCond.Signal)
  234. }
  235. this.dataInputCond.L.Lock()
  236. this.dataInputCond.Wait()
  237. this.dataInputCond.L.Unlock()
  238. if timer != nil {
  239. timer.Stop()
  240. }
  241. if !this.rd.IsZero() && this.rd.Before(time.Now()) {
  242. return 0, ErrIOTimeout
  243. }
  244. }
  245. }
  246. // Write implements the Conn Write method.
  247. func (this *Connection) Write(b []byte) (int, error) {
  248. totalWritten := 0
  249. for {
  250. if this == nil || this.State() != StateActive {
  251. return totalWritten, io.ErrClosedPipe
  252. }
  253. nBytes := this.sendingWorker.Push(b[totalWritten:])
  254. this.dataUpdater.WakeUp()
  255. if nBytes > 0 {
  256. totalWritten += nBytes
  257. if totalWritten == len(b) {
  258. return totalWritten, nil
  259. }
  260. }
  261. var timer *time.Timer
  262. if !this.wd.IsZero() {
  263. duration := this.wd.Sub(time.Now())
  264. if duration <= 0 {
  265. return totalWritten, ErrIOTimeout
  266. }
  267. timer = time.AfterFunc(duration, this.dataOutputCond.Signal)
  268. }
  269. this.dataOutputCond.L.Lock()
  270. this.dataOutputCond.Wait()
  271. this.dataOutputCond.L.Unlock()
  272. if timer != nil {
  273. timer.Stop()
  274. }
  275. if !this.wd.IsZero() && this.wd.Before(time.Now()) {
  276. return totalWritten, ErrIOTimeout
  277. }
  278. }
  279. }
  280. func (this *Connection) SetState(state State) {
  281. current := this.Elapsed()
  282. atomic.StoreInt32((*int32)(&this.state), int32(state))
  283. atomic.StoreUint32(&this.stateBeginTime, current)
  284. log.Debug("KCP|Connection: #", this.conv, " entering state ", state, " at ", current)
  285. switch state {
  286. case StateReadyToClose:
  287. this.receivingWorker.CloseRead()
  288. this.dataUpdater.WakeUp()
  289. case StatePeerClosed:
  290. this.sendingWorker.CloseWrite()
  291. this.dataUpdater.WakeUp()
  292. case StateTerminating:
  293. this.receivingWorker.CloseRead()
  294. this.sendingWorker.CloseWrite()
  295. this.dataUpdater.interval = time.Second
  296. this.dataUpdater.WakeUp()
  297. case StatePeerTerminating:
  298. this.sendingWorker.CloseWrite()
  299. this.dataUpdater.WakeUp()
  300. case StateTerminated:
  301. this.receivingWorker.CloseRead()
  302. this.sendingWorker.CloseWrite()
  303. this.dataUpdater.interval = time.Second
  304. this.dataUpdater.WakeUp()
  305. this.Terminate()
  306. }
  307. }
  308. // Close closes the connection.
  309. func (this *Connection) Close() error {
  310. if this == nil {
  311. return ErrClosedConnection
  312. }
  313. this.dataInputCond.Broadcast()
  314. this.dataOutputCond.Broadcast()
  315. state := this.State()
  316. if state.Is(StateReadyToClose, StateTerminating, StateTerminated) {
  317. return ErrClosedConnection
  318. }
  319. log.Info("KCP|Connection: Closing connection to ", this.remote)
  320. if state == StateActive {
  321. this.SetState(StateReadyToClose)
  322. }
  323. if state == StatePeerClosed {
  324. this.SetState(StateTerminating)
  325. }
  326. if state == StatePeerTerminating {
  327. this.SetState(StateTerminated)
  328. }
  329. return nil
  330. }
  331. // LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
  332. func (this *Connection) LocalAddr() net.Addr {
  333. if this == nil {
  334. return nil
  335. }
  336. return this.local
  337. }
  338. // RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
  339. func (this *Connection) RemoteAddr() net.Addr {
  340. if this == nil {
  341. return nil
  342. }
  343. return this.remote
  344. }
  345. // SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
  346. func (this *Connection) SetDeadline(t time.Time) error {
  347. if err := this.SetReadDeadline(t); err != nil {
  348. return err
  349. }
  350. if err := this.SetWriteDeadline(t); err != nil {
  351. return err
  352. }
  353. return nil
  354. }
  355. // SetReadDeadline implements the Conn SetReadDeadline method.
  356. func (this *Connection) SetReadDeadline(t time.Time) error {
  357. if this == nil || this.State() != StateActive {
  358. return ErrClosedConnection
  359. }
  360. this.rd = t
  361. return nil
  362. }
  363. // SetWriteDeadline implements the Conn SetWriteDeadline method.
  364. func (this *Connection) SetWriteDeadline(t time.Time) error {
  365. if this == nil || this.State() != StateActive {
  366. return ErrClosedConnection
  367. }
  368. this.wd = t
  369. return nil
  370. }
  371. // kcp update, input loop
  372. func (this *Connection) updateTask() {
  373. this.flush()
  374. }
  375. func (this *Connection) FetchInputFrom(conn io.Reader) {
  376. go func() {
  377. payload := alloc.NewLocalBuffer(2048)
  378. defer payload.Release()
  379. for this.State() != StateTerminated {
  380. payload.Reset()
  381. nBytes, err := conn.Read(payload.Value)
  382. if err != nil {
  383. return
  384. }
  385. payload.Slice(0, nBytes)
  386. if this.block.Open(payload) {
  387. this.Input(payload.Value)
  388. }
  389. }
  390. }()
  391. }
  392. func (this *Connection) Reusable() bool {
  393. return false
  394. }
  395. func (this *Connection) SetReusable(b bool) {}
  396. func (this *Connection) Terminate() {
  397. if this == nil || this.writer == nil {
  398. return
  399. }
  400. log.Info("KCP|Connection: Terminating connection to ", this.RemoteAddr())
  401. //this.SetState(StateTerminated)
  402. this.dataInputCond.Broadcast()
  403. this.dataOutputCond.Broadcast()
  404. this.writer.Close()
  405. }
  406. func (this *Connection) HandleOption(opt SegmentOption) {
  407. if (opt & SegmentOptionClose) == SegmentOptionClose {
  408. this.OnPeerClosed()
  409. }
  410. }
  411. func (this *Connection) OnPeerClosed() {
  412. state := this.State()
  413. if state == StateReadyToClose {
  414. this.SetState(StateTerminating)
  415. }
  416. if state == StateActive {
  417. this.SetState(StatePeerClosed)
  418. }
  419. }
  420. // Input when you received a low level packet (eg. UDP packet), call it
  421. func (this *Connection) Input(data []byte) int {
  422. current := this.Elapsed()
  423. atomic.StoreUint32(&this.lastIncomingTime, current)
  424. this.dataUpdater.WakeUp()
  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. case *AckSegment:
  437. this.HandleOption(seg.Option)
  438. this.sendingWorker.ProcessSegment(current, seg)
  439. this.dataOutputCond.Signal()
  440. case *CmdOnlySegment:
  441. this.HandleOption(seg.Option)
  442. if seg.Command == CommandTerminate {
  443. state := this.State()
  444. if state == StateActive ||
  445. state == StatePeerClosed {
  446. this.SetState(StatePeerTerminating)
  447. } else if state == StateReadyToClose {
  448. this.SetState(StateTerminating)
  449. } else if state == StateTerminating {
  450. this.SetState(StateTerminated)
  451. }
  452. }
  453. this.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
  454. this.receivingWorker.ProcessSendingNext(seg.SendingNext)
  455. this.roundTrip.UpdatePeerRTO(seg.PeerRTO, current)
  456. seg.Release()
  457. default:
  458. }
  459. }
  460. return 0
  461. }
  462. func (this *Connection) flush() {
  463. current := this.Elapsed()
  464. if this.State() == StateTerminated {
  465. return
  466. }
  467. if this.State() == StateActive && current-atomic.LoadUint32(&this.lastIncomingTime) >= 30000 {
  468. this.Close()
  469. }
  470. if this.State() == StateReadyToClose && this.sendingWorker.IsEmpty() {
  471. this.SetState(StateTerminating)
  472. }
  473. if this.State() == StateTerminating {
  474. log.Debug("KCP|Connection: #", this.conv, " sending terminating cmd.")
  475. seg := NewCmdOnlySegment()
  476. defer seg.Release()
  477. seg.Conv = this.conv
  478. seg.Command = CommandTerminate
  479. this.output.Write(seg)
  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) >= 3000 {
  496. seg := NewCmdOnlySegment()
  497. seg.Conv = this.conv
  498. seg.Command = CommandPing
  499. seg.ReceivinNext = this.receivingWorker.nextNumber
  500. seg.SendingNext = this.sendingWorker.firstUnacknowledged
  501. seg.PeerRTO = this.roundTrip.Timeout()
  502. if this.State() == StateReadyToClose {
  503. seg.Option = SegmentOptionClose
  504. }
  505. this.output.Write(seg)
  506. this.lastPingTime = current
  507. seg.Release()
  508. }
  509. // flash remain segments
  510. this.output.Flush()
  511. }
  512. func (this *Connection) State() State {
  513. return State(atomic.LoadInt32((*int32)(&this.state)))
  514. }