connection.go 12 KB

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