connection.go 12 KB

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