connection.go 13 KB

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